/**
 * 
 */
package com.cqan.security;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.cqan.account.entity.User;
import com.cqan.account.service.UserService;
import com.cqan.util.encode.EncodeUtils;



/**
 * @author wuhui
 *
 * 上午11:45:08
 */
public class UserAuthenticationFilter extends
		UsernamePasswordAuthenticationFilter {
	public static final String VALIDATE_CODE = "validateCode";
	public static final String USERNAME = "username";
	public static final String PASSWORD = "password";
	
	@Resource(name="userService")
	private UserService userService;

	
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
		if (!request.getMethod().equals("POST")) {
			throw new AuthenticationServiceException("不支持这种请求方式: " + request.getMethod());
		}
		
		checkValidateCode(request);
		
		String username = obtainUsername(request);
		String password = obtainPassword(request);
		
		//验证用户账号与密码是否对应
		username = username.trim();
		
		User user = userService.getUserByUserName(username);
		if(user == null) {
			throw new AuthenticationServiceException("*用户名不存在!"); 
		}
		if(!user.isAccountNonLocked()) {
			throw new AuthenticationServiceException("*该用户已被锁定,请联系系统管理员!"); 
		}
		if(!user.isAccountNonExpired()) {
			throw new AuthenticationServiceException("*该用户已过期,请联系系统管理员!"); 
		}
		
		if(!user.isSpecial()) {
			throw new AuthenticationServiceException("*您没有登陆权限!"); 
		}
		
		if(!user.getPassword().equals(EncodeUtils.md5(password, username))){
			
			throw new AuthenticationServiceException("*用户名或密码不正确!"); 
		}
		
		//UsernamePasswordAuthenticationToken实现 Authentication
		UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
		// Place the last username attempted into HttpSession for views
		
		// 允许子类设置详细属性
        setDetails(request, authRequest);
        
        // 运行UserDetailsService的loadUserByUsername 再次封装Authentication
		return this.getAuthenticationManager().authenticate(authRequest);

	}
	
	protected void checkValidateCode(HttpServletRequest request) { 
		HttpSession session = request.getSession();
	    String sessionValidateCode = obtainSessionValidateCode(session); 
	    //让上一次的验证码失效
	    session.setAttribute(VALIDATE_CODE, null);
	    String validateCodeParameter = obtainValidateCodeParameter(request);  
	    if (StringUtils.isEmpty(validateCodeParameter) || !sessionValidateCode.equalsIgnoreCase(validateCodeParameter)) {  
	        throw new AuthenticationServiceException("*验证码不正确!");  
	    }  
	}
	
	private String obtainValidateCodeParameter(HttpServletRequest request) {
		Object obj = request.getParameter(VALIDATE_CODE);
		return null == obj ? "" : obj.toString();
	}

	protected String obtainSessionValidateCode(HttpSession session) {
		Object obj = session.getAttribute(VALIDATE_CODE);
		return null == obj ? "" : obj.toString();
	}

	@Override
	protected String obtainUsername(HttpServletRequest request) {
		Object obj = request.getParameter(USERNAME);
		return null == obj ? "" : obj.toString();
	}

	@Override
	protected String obtainPassword(HttpServletRequest request) {
		String obj = request.getParameter(PASSWORD);
		return null == obj ? "" : obj.toString();
	}
}
